package com.gzhryc.shared_device.oem.micro.iot.jetty;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.shared_device.iot.core.IOTClient;
import com.gzhryc.shared_device.iot.core.IOTNodeEntity;
import com.gzhryc.shared_device.oem.micro.iot.IOTServerNodeFactory;
import com.gzhryc.shared_device.oem.micro.iot.MicroConstants;
import com.gzhryc.servlet.WebUtils;
import org.apache.commons.lang3.StringUtils;

public class SecurityFilter implements Filter{

	private static Pattern _Pat = Pattern.compile("^/iot/(\\d+)(/.*)$");

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		String uri = httpRequest.getRequestURI();
		if (uri.contains("/favicon.ico")) {
			return;
		}

		Matcher mat = _Pat.matcher(uri);
		if (mat.find()) {
			Long iotId = Long.valueOf(mat.group(1));
			IOTClient iotClient = IOTServerNodeFactory.self().getIOTClient(iotId);
			if (iotClient != null) {
				String loginToken = httpRequest.getHeader("authorization");
				if (StringUtils.isNotBlank(loginToken) && loginToken.equals(iotClient.getIOTNote().getApiToken())) {
					httpRequest.setAttribute("uri", mat.group(2));
					httpRequest.setAttribute(MicroConstants.ATTR_IOT_ID, iotId);
					chain.doFilter(httpRequest, httpResponse);
					return;
				} else {
					DefaultAPIResponse result = new DefaultAPIResponse(DefaultAPICodeConstants.TOKEN_ERROR, "无权限");
					WebUtils.toJson(httpResponse, result);
					return;
				}
			} else {
				DefaultAPIResponse result = new DefaultAPIResponse(DefaultAPICodeConstants.NOT_FIND,"未找到IOT服务");
				WebUtils.toJson(httpResponse, result);
				return;
			}
		}
		DefaultAPIResponse result = new DefaultAPIResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"执行错误");
		WebUtils.toJson(httpResponse, result);
		return;
	}

	@Override
	public void destroy() {}
}
